<template>
  <div class="no-background-container">
    <header-component />
    <el-affix :offset="72">
      <div class="qs-y-table-header align-center">
        <div class="header-label flex-1 min-w-50">
          <div class="header-label-title">{{ routeName }}</div>
        </div>
        <div class="header-query">
          <el-button type="primary" @click="handleAdd">新增{{ moduleName }}</el-button>
          <el-form class="query-form" :inline="true" :model="queryForm" @submit.prevent="handleSearch">
            <el-form-item>
              <el-input v-model="queryForm.search" clearable placeholder="搜索会议主题" @keyup.enter="handleSearch" />
            </el-form-item>
            <el-form-item>
              <el-select v-model="queryForm.location" clearable placeholder="选择会议室">
                <el-option v-for="option in locationOptions" :key="option.value" :label="option.label" :value="option.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-affix>

    <div class="qs-y-table-card">
      <!-- 使用新的Table组件 -->
      <qs-table
        border
        :columns="tableState.visibleColumns"
        :data="tableState.data"
        :loading="tableState.loading"
        :pagination="{
          currentPage: tableState.pagination.currentPage,
          pageSize: tableState.pagination.pageSize,
          total: tableState.pagination.total,
          layout: 'total, sizes, prev, pager, next, jumper',
        }"
        :selection="{
          show: true,
          selectedRows: tableState.selection.selectedRows,
        }"
        show-index
        stripe
        @page-change="handlePageChange"
        @row-click="handleRowClick"
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
      >
        <!-- 自定义列渲染 -->
        <template #column-meetingTitle="{ row }">
          <div style="cursor: pointer" @click="handleDetails(row)">
            <div style="font-size: 14px; font-weight: 500; color: var(--el-color-primary)">
              {{ row.meetingTitle }}
            </div>
            <div style="font-size: 12px">{{ row.date }} {{ row.startTime }}</div>
          </div>
        </template>
        <template #column-attendees="{ row }">
          <el-tag v-for="(attendee, index) in row.attendees" :key="index" style="margin-right: 5px; margin-bottom: 5px">
            {{ attendee }}
          </el-tag>
        </template>
        <!-- 操作列 -->
        <template #operations="{ row }">
          <el-button size="small" text @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" text type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </qs-table>
    </div>

    <!-- 使用新的FormDialog组件 -->
    <qs-form-dialog
      v-model="dialogState.visible"
      :confirm-loading="dialogState.confirmLoading"
      :fields="fields"
      :form-data="dialogState.formData"
      :loading="dialogState.loading"
      :title="dialogState.title"
      @cancel="handleFormCancel"
      @confirm="handleFormSubmit"
    >
      <!-- 自定义表单元素渲染 -->
      <template #field-attendees="{ field, form }">
        <el-select
          v-model="form.attendees"
          allow-create
          default-first-option
          filterable
          multiple
          placeholder="请选择或输入与会人员"
          style="width: 100%"
        >
          <el-option v-for="attendee in attendeeOptions" :key="attendee.value" :label="attendee.label" :value="attendee.value" />
        </el-select>
      </template>
    </qs-form-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import QsFormDialog from '../../components/Dialog-new/FormDialog.vue'
import QsTable from '../../components/Table-new/index.vue'
import { useDialog } from '../../hooks/useDialog'
import { useTable } from '../../hooks/useTable'
import HeaderComponent from '../home/components/header.vue'
// 路由相关
const route = useRoute()
const router = useRouter()
const routeName = computed(() => route.meta.title || '会议室预约')

// 模块名称
const moduleName = ref('预约')

// 模拟数据
const mockData = [
  {
    id: 1,
    meetingTitle: '项目进度会议',
    date: '2023-10-01',
    startTime: '09:00:00',
    duration: 60,
    location: '会议室A',
    attendees: ['张三', '李四', '王五'],
    description: '讨论项目进度和下一步计划',
  },
  {
    id: 2,
    meetingTitle: '客户会议',
    date: '2023-10-02',
    startTime: '10:00:00',
    duration: 90,
    location: '会议室B',
    attendees: ['赵六', '孙七', '周八'],
    description: '与客户讨论合作细节',
  },
  {
    id: 3,
    meetingTitle: '内部培训',
    date: '2023-10-03',
    startTime: '14:00:00',
    duration: 120,
    location: '会议室A',
    attendees: ['吴九', '郑十', '钱十一'],
    description: '进行内部员工培训',
  },
  {
    id: 4,
    meetingTitle: '产品发布会',
    date: '2023-10-04',
    startTime: '09:30:00',
    duration: 180,
    location: '会议室B',
    attendees: ['王十二', '李十三', '张十四'],
    description: '发布新产品',
  },
  {
    id: 5,
    meetingTitle: '团队建设活动',
    date: '2023-10-05',
    startTime: '10:30:00',
    duration: 150,
    location: '会议室A',
    attendees: ['赵十五', '孙十六', '周十七'],
    description: '组织团队建设活动',
  },
]

// 会议室选项
const locationOptions = [
  { value: '会议室A', label: '会议室A' },
  { value: '会议室B', label: '会议室B' },
]

// 与会人员选项
const attendeeOptions = [
  { value: '张三', label: '张三' },
  { value: '李四', label: '李四' },
  { value: '王五', label: '王五' },
  { value: '赵六', label: '赵六' },
  { value: '孙七', label: '孙七' },
]

// 表单字段定义
const fields = [
  {
    label: '会议主题',
    prop: 'meetingTitle',
    component: 'input',
    required: true,
    placeholder: '请输入会议主题',
    colSpan: 24,
  },
  {
    label: '日期',
    prop: 'date',
    component: 'date-picker',
    required: true,
    placeholder: '请选择日期',
    colSpan: 12,
  },
  {
    label: '开始时间',
    prop: 'startTime',
    component: 'time-picker',
    required: true,
    placeholder: '请选择开始时间',
    colSpan: 12,
  },
  {
    label: '时长',
    prop: 'duration',
    component: 'input-number',
    required: true,
    placeholder: '请输入时长（分钟）',
    min: 15,
    max: 480,
    step: 15,
    colSpan: 12,
  },
  {
    label: '会议室',
    prop: 'location',
    component: 'select',
    options: locationOptions,
    required: true,
    placeholder: '请选择会议室或地点',
    colSpan: 12,
  },
  {
    label: '与会人员',
    prop: 'attendees',
    component: 'attendee-selector', // 使用插槽自定义渲染
    required: true,
    placeholder: '请选择或输入与会人员',
    colSpan: 24,
  },
  {
    label: '会议描述',
    prop: 'description',
    component: 'textarea',
    required: true,
    placeholder: '请输入会议描述',
    colSpan: 24,
    rows: 4,
  },
]

// 表格列定义
const columns = [
  {
    label: '会议主题',
    prop: 'meetingTitle',
    minWidth: 220,
    customRender: true, // 使用自定义渲染
  },
  {
    label: '日期',
    prop: 'date',
    minWidth: 120,
  },
  {
    label: '时间',
    prop: 'startTime',
    minWidth: 120,
  },
  {
    label: '时长(分钟)',
    prop: 'duration',
    minWidth: 100,
  },
  {
    label: '会议室',
    prop: 'location',
    minWidth: 120,
  },
  {
    label: '与会人员',
    prop: 'attendees',
    minWidth: 200,
    customRender: true, // 使用自定义渲染
  },
  {
    label: '描述',
    prop: 'description',
    minWidth: 200,
  },
]

// 查询表单
const queryForm = reactive({
  search: '',
  location: '',
  page: 1,
  limit: 20,
})

// 使用表格Hook
const {
  data: tableData,
  loading: tableLoading,
  pagination,
  selection,
  visibleColumns,
  setData,
  setLoading,
  setPagination,
  setSelectedRows,
} = useTable({
  columns,
  showOperations: true,
})

// 表格状态集合，方便模板引用
const tableState = reactive({
  data: tableData,
  loading: tableLoading,
  pagination,
  selection,
  visibleColumns,
})

// 使用对话框Hook
const {
  visible: dialogVisible,
  title: dialogTitle,
  loading: dialogLoading,
  setTitle,
  open: openDialog,
  close: closeDialog,
} = useDialog({
  title: '新增预约',
})

// 表单数据
const formData = ref({})
const confirmLoading = ref(false)

// 对话框状态集合，方便模板引用
const dialogState = reactive({
  visible: dialogVisible,
  title: dialogTitle,
  formData,
  loading: dialogLoading,
  confirmLoading,
})

// 是否为编辑模式
const isEditMode = ref(false)

// 获取数据
const fetchData = async () => {
  setLoading(true)
  try {
    // 在实际应用中，这里应该是从API获取数据
    const filteredData = mockData.filter((item) => {
      const searchMatch = !queryForm.search || item.meetingTitle.includes(queryForm.search)
      const locationMatch = !queryForm.location || item.location === queryForm.location
      return searchMatch && locationMatch
    })

    const { page, limit } = queryForm
    const start = (page - 1) * limit
    const end = start + limit
    const paginatedData = filteredData.slice(start, end)

    setData(paginatedData)
    setPagination({
      currentPage: page,
      pageSize: limit,
      total: filteredData.length,
    })
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    setLoading(false)
  }
}

// 处理页码变化
const handlePageChange = (page: number) => {
  queryForm.page = page
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  queryForm.limit = size
  queryForm.page = 1
  fetchData()
}

// 处理选择行变化
const handleSelectionChange = (rows: any[]) => {
  setSelectedRows(rows)
}

// 处理行点击
const handleRowClick = (row: any) => {
  // 可以在这里处理行点击事件
}

// 查看详情
const handleDetails = (row: any) => {
  ElMessage.info(`查看 ${row.meetingTitle} 的详情`)
  // 实际应用中可以跳转到详情页
  // router.push({ name: 'ReserveDetail', params: { id: row.id } });
}

// 处理搜索
const handleSearch = () => {
  queryForm.page = 1
  fetchData()
}

// 重置搜索条件
const handleReset = () => {
  queryForm.search = ''
  queryForm.location = ''
  queryForm.page = 1
  fetchData()
}

// 添加数据
const handleAdd = () => {
  isEditMode.value = false
  formData.value = {
    meetingTitle: '',
    date: '',
    startTime: '',
    duration: 60,
    location: '',
    attendees: [],
    description: '',
  }
  setTitle(`新增${moduleName.value}`)
  openDialog()
}

// 编辑数据
const handleEdit = (row: any) => {
  isEditMode.value = true
  formData.value = { ...row }
  setTitle(`编辑${moduleName.value}`)
  openDialog()
}

// 删除数据
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除 "${row.meetingTitle}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 在实际应用中，这里应该调用API删除数据
      // 模拟删除成功
      ElMessage.success('删除成功')
      fetchData()
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 提交表单
const handleFormSubmit = async (form: any) => {
  confirmLoading.value = true
  try {
    // 在实际应用中，这里应该调用API保存数据
    console.log('提交的表单数据:', form)

    // 模拟API调用延迟
    await new Promise((resolve) => setTimeout(resolve, 1000))

    ElMessage.success(isEditMode.value ? '更新成功' : '添加成功')
    closeDialog()
    fetchData()
  } catch (error) {
    console.error('保存数据失败:', error)
    ElMessage.error('保存失败')
  } finally {
    confirmLoading.value = false
  }
}

// 取消表单
const handleFormCancel = () => {
  closeDialog()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.query-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.qs-y-table-card {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-top: 77px !important;
}

.header-label {
  display: flex;
  align-items: center;
}

.header-label-title {
  font-size: 18px;
  font-weight: 500;
}

.header-query {
  display: flex;
  align-items: center;
  gap: 16px;
}
</style>
